package cn.itcast.listener;

import static org.quartz.CronScheduleBuilder.cronSchedule;  
import static org.quartz.JobBuilder.newJob;  
import static org.quartz.TriggerBuilder.newTrigger;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

import cn.itcast.utils.SimpleJob;

/**
 * Application Lifecycle Listener implementation class QuartzListener
 *
 */
@WebListener
public class QuartzListener implements ServletContextListener {

    /**
     * Default constructor. 
     */
    public QuartzListener() {
        // TODO Auto-generated constructor stub
    }

	/**
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent arg0)  { 
         // TODO Auto-generated method stub
        // 日期格式化  

        SimpleDateFormat dateFormat = new SimpleDateFormat(  
                "yyyy 年 MM 月 dd 日  HH 时 mm 分 ss 秒");  
  
        SchedulerFactory sf = new StdSchedulerFactory();  
        Scheduler sched = null;
		try {
			sched = sf.getScheduler();
		} catch (SchedulerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
        System.out.println("--------------- 初始化 -------------------");  
  
        // job1 每3s运行一次  

        JobDetail job = newJob(SimpleJob.class).withIdentity("job1", "group1")  
                .build();  
  
        CronTrigger trigger = newTrigger().withIdentity("trigger1", "group1")  
                .withSchedule(cronSchedule("0/3 * * * * ?")).build();  
  
       
		try {
			 Date ft = sched.scheduleJob(job, trigger);
		        System.out.println(job.getKey().getName() + " 将在: "  
		                + dateFormat.format(ft) + " 运行 . 并且基于Cron表达式 : "  
		                + trigger.getCronExpression() + "  (含义:每3s运行一次)");  
		        
	        sched.start();  
		        
	        System.out.println("------- 开始调度 (调用.start()方法) ----------------");  
		} catch (SchedulerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  


    }

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	
}
